<?php 
	class ImageUtil {
		public $image; 
		
		public function destroy(){
			if($this->image != null){
				$res = imagedestroy($this->image);
				
				if(!$res){
					throw new Exception("Failure to destroy the image"); 
				}
				
				$this->image = null;
			}
			else {
				throw new Exception('The image to destroy is not initialized');
			}
		}
		
		public function loadImage($file){
			$res = imagecreatefromjpeg($file);
			
			if($res){
				$this->image = $res; 
			}
			else {
				throw new Exception('Error while loading image, possible invalid image');
			}
		}
		
		public function saveImage($file, $dimension){
			$x = imagesx($this->image);
			$y = imagesy($this->image);
			
			$max = $x > $y ? $x : $y;
			
			if($dimension > $max){
				// we don't resize, we just copy the file as is
				imagejpeg($this->image, $file);
			}
			else {
				// resize the file accordingly
				$quotient = $dimension / $max;
				
				$finalX = $quotient * $x; 
				$finalY = $quotient * $y;
				
				$result = imagecreatetruecolor($finalX, $finalY);
				imagecopyresampled($result, $this->image, 0, 0, 0, 0, $finalX, $finalY, $x, $y);

				imagejpeg($result, $file);
				imagedestroy($result);
			}
		}
	}
?>